package psn.qiuyiping.autocad.dxffile;

import java.io.IOException;
import java.util.Map;
import java.util.Stack;

import com.cbf4file.ClassUtils;

public class DxfProcessContext
        extends Stack<DxfProcessFunc> {
    static final Map<String, Class<? extends DefaultDxf0>> DXF0FUNCS;
    public static final int                                TOP = 1;
    static {
        DXF0FUNCS = new java.util.TreeMap<>();
        registerPackage(DxfProcessContext.class.getPackage().getName());
    }

    public static void registerPackage(String packName) {
        try {
            for (Class<?> cls : ClassUtils.getClasses(packName)) {
                Dxf0Name f = cls.getAnnotation(Dxf0Name.class);
                if (f == null) {
                    continue;
                }
                DXF0FUNCS.put(f.value(), (Class<? extends SectionDefault>) cls);
            }
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    DxfTable currentTable;
    DxfFile  file;

    public DxfProcessContext() {
        file = new DxfFile();
    }

    public DxfTable getCurrentTable() {
        return currentTable;
    }

    public DxfFile getFile() {
        return file;
    }

    public void process(DxfData<Object> dxf0) {
        if (this.isEmpty()) {
            this.processDxf0(dxf0);
        } else {
            peek().readDxf(this, dxf0);
        }
    }

    public void processDxf0(DxfData<Object> dxf0) {
        this.clear();
        String name = (String) dxf0.getVal();
        Class<? extends DefaultDxf0> cls = DXF0FUNCS.get(name);
        if (cls == null) {
            System.out.println("class:"+name);
            cls = DefaultDxf0.class;
            DXF0FUNCS.put(name, cls);
            push(new DefaultDxf0());
        } else {
            try {
                push(cls.newInstance());
            } catch (InstantiationException | IllegalAccessException e) {
                System.out.println(dxf0.getVal());
                push(new DefaultDxf0());
                e.printStackTrace();
            }
        }
    }

    public void setCurrentTable(DxfTable currentTable) {
        this.currentTable = currentTable;
    }

}
